package mobi.greenplate.theweb.web;

import java.io.Serializable;
import java.util.List;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.WebApplicationContext;

import org.deltaset.faces.FacesUtils;
import org.deltaset.faces.PageHelper;

import mobi.greenplate.theweb.domain.Address;
import mobi.greenplate.theweb.repository.AddressRepository;

//for : enum types (and many-to-one)



@ManagedBean("addressBean")
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class AddressBean implements Serializable {

    private static final String OUTCOME_DETAIL = "/secured/address/detail?faces-redirect=true&addressId=%s";
    private static final String OUTCOME_LIST = "/secured/address/list?faces-redirect=true";
    private static final long serialVersionUID = 1L;


    @Inject
    public AddressBean(final AddressRepository modelRepository) {
        this.modelRepository = modelRepository;
    }
    private final AddressRepository modelRepository;
	
	
	public Address loadModel(String id) {
        if (null != id && !"".equals(id.trim())) {
            return modelRepository.findById(Long.valueOf(id));
        }
        return new Address();
    }

    public boolean isNew(Address model) {
        return null == model.getId();
    }

    public String delete(Address model) {
        modelRepository.delete(model.getId());
        return OUTCOME_LIST;
    }
    
   public void deleteAndReset(Address model, PageHelper<Address> pageHelper) {
        delete(model);
        pageHelper.reset();
    }

    public String save(Address model) {
        final Address saved = modelRepository.save(model);
        return String.format(OUTCOME_DETAIL, saved.getId().toString());
    }

    //always here. actually provides support for one-to-Many
    public void setModelTo(Address model, String valueExpression){
        FacesUtils.setValueExpression(valueExpression,model);
    }
	



/// List handlers

    public PageHelper<Address> all(String pageNum) {
        return all.load(pageNum);
    }
    private PageHelper<Address> all = PageHelper.newInstance(new AllFinder());

    private static class AllFinder implements PageHelper.Finder<Address> {

        private static final long serialVersionUID = 1L;

        public int counter(Object... params) {
            return FacesUtils.getManagedBean("addressRepository", AddressRepository.class).countAll();
        }

        public List<Address> finder(int firstResult, int maxResult, Object... params) {
            return FacesUtils.getManagedBean("addressRepository", AddressRepository.class).
                    findAll(firstResult, maxResult);
        }
    }
	

	

    
}
